<template>
  <Modal class="caggiage-goods-modal" v-model="modal" :title="title" fullscreen :mask-closable="false" :mask="false">
    <p class="caggiage-top-title"><Icon class="icon" type="ios-alert" />设置默认模板后，若商品没有绑定运费模板，按默认模板收取运费</p>
    <div class="form-content">
        <Form :model="form" :label-width="100" ref="form" :rules="rules">
            <FormItem label="模板名称" prop="freightName">
              <Input v-model.trim="form.freightName" placeholder="模板名称..." />
            </FormItem>
            <FormItem label="是否包邮">
              <RadioGroup v-model="form.freightCover" @on-change="onChange">
                <Radio label="BUYER_BEAR">买家承担运费</Radio>
                <Radio label="SELLER_BEAR">卖家承担运费</Radio>
              </RadioGroup>
            </FormItem>
            <div v-show="form.freightCover==='BUYER_BEAR'">
              <FormItem label="计费规则">
                <RadioGroup v-model="form.freightRule" @on-change="onChangeRule">
                  <Radio label="ITEM">按件数</Radio>
                  <Radio label="WEIGHT">按重量</Radio>
                </RadioGroup>
                <p class="font-blue">除指定地区外，其余地区的运费采用“默认运费”</p>
                <p><Checkbox v-model="single" disabled>配送</Checkbox></p>
                <div class="mt mb"><Button type="primary" size="small" @click="onAddDealer('delivery')">为指定经销商设置运费</Button></div>
                <template v-if="form.freightRule==='ITEM'">
                  <div class="table-top min-w1200">
                    <div class="bottom">
                      国内默认运费<InputNumber class="ml mr" v-model="defaultNum1" :min="0" :precision="0" />件内， <InputNumber class="mr" v-model="defaultFee1" :min="0" :precision="2" />元，每增加 <InputNumber  class="ml mr" v-model="extraNum1" :min="0" :precision="0" />件，增加运费 <InputNumber class="ml mr" v-model="extraFee1" :min="0" :precision="2" />元，配送描述 <Input class="w500 ml" v-model="deliveryDescribe1" @on-blur="onBlur('deliveryDescribe1', 1)" :maxlength="100" placeholder="最多100字" />
                    </div>
                    <div v-if="!isDefault">
                      <p class="link" @click="onEdit({_index: 1, distributorDTOS: defaultdistributorDTOS1}, 'default')">为指定经销商设置默认运费</p>
                      <span class="red">{{defaultdistributorDTOS1 | fliterDis}}</span>
                    </div>
                  </div>
                  <Table class="min-w1200" border :columns="columns" :data="data1"></Table>
                </template>
                <template v-else>
                  <div class="table-top min-w1200">
                    <div class="bottom">
                      国内默认运费 <InputNumber class="ml mr" v-model="defaultNum2" :min="0" :precision="0" />kg内，<InputNumber class="mr" v-model="defaultFee2" :min="0" :precision="2" />元，每增加 <InputNumber class="ml mr" v-model="extraNum2" :min="0" :precision="0" />kg，增加运费 <InputNumber class="ml mr" v-model="extraFee2" :min="0" :precision="2" />元，配送描述 <Input class="w500 ml" v-model="deliveryDescribe2" @on-blur="onBlur('deliveryDescribe2', 1)" :maxlength="100" placeholder="最多100字" />
                    </div>
                    <div v-if="!isDefault">
                      <p class="link" @click="onEdit({_index: 2, distributorDTOS: defaultdistributorDTOS2}, 'default')">为指定经销商设置默认运费</p>
                      <span class="red">{{defaultdistributorDTOS2 | fliterDis}}</span>
                    </div>
                  </div>
                  <Table class="min-w1200" border :columns="columns3" :data="data2"></Table>
                </template>
              </FormItem>
              <FormItem label="按件免邮">
                <Checkbox v-model="isOpenFree">按件免邮</Checkbox>
                <div class="mt mb"><Button size="small" type="primary" @click="onAddDealer('postage')">添加经销商</Button></div>
                <div v-show="isOpenFree && form.freightRule==='ITEM'">
                  <Table class="min-w1200" border :columns="columns2" :data="data3"></Table>
                </div>
                <div v-show="isOpenFree && form.freightRule==='WEIGHT'">
                  <Table class="min-w1200" border :columns="columns2" :data="data4"></Table>
                </div>
              </FormItem>
            </div>
        </Form>
    </div>
    <div slot="footer">
      <Button :disabled="disabled" @click="onSave" type="primary" size="large">保存且返回</Button>
      <Button @click="modal = false" size="large" type="text">返回</Button>
    </div>
    <DealerChange ref="dealer-change" @onComplete="onComplete"/>
</Modal>
</template>
<script>
import DealerChange from './DealerChange'
import { renderButton } from '@/util';
import { Input, InputNumber } from 'view-design'
export default {
  components: {
    DealerChange
  },
  data() {
    const validateName = (rule, value, callback) => {
      if (value.trim() === '') {
        callback(new Error('请输入模板名称'));
      } else {
        this.checkOnly().then(() =>{
          if (this.flag) {
            callback(new Error('模板名称不可重复'));
          } else {
            callback();
          }
        })   
      }
    }
    return {
      modal: false,
      isDefault: false,
      id: null,
      title: '',
      disabled: false,
      single: true,
      maxlength: 100,
      originalData: {},
      form: {
        freightName: '',
        freightCover: 'BUYER_BEAR',
        freightRule: 'ITEM'
      },
      id1: null,
      defaultdistributorDTOS1: [],
      defaultNum1: null,
      defaultFee1: null,
      extraNum1: null,
      extraFee1: null,
      deliveryDescribe1: '',
      id2: null,
      defaultdistributorDTOS2: [],
      defaultNum2: null,
      defaultFee2: null,
      extraNum2: null,
      extraFee2: null,
      deliveryDescribe2: '',
      flag: false,
      rules: {
        freightName: [
          { required: true, validator: validateName, trigger: "blur" }
        ]
      },
      columns: [{
        title: '经销商',
        key: 'distributorDTOS',
        minWidth: 100,
        render: (h, p) => {
          let text = ''
          if (p.row.distributorDTOS && p.row.distributorDTOS.length) {
            p.row.distributorDTOS.forEach(item => {
              text += item.value + ','
            })
          }
          if (text.length) text = text.substring(0, text.length - 1)
          return (
            <div>
              <p>{text}</p>
              {renderButton(h, {text: '编辑', type: 'primary', size: 'small'}, () => this.onEdit(p.row, 'delivery'))}
            </div>
            )
        }
      }, {
        title: '首件(个)',
        key: 'defaultNum',
        width: 120,
        align: 'center',
        render: (h, p) => {
          return this.renderInputNumber(h, {key: 'defaultNum', v: p.row.defaultNum, row: p.row, min: 1, precision: 0})
        }
      }, {
        title: '首费(元)',
        key: 'defaultFee',
        width: 120,
        align: 'center',
        render: (h, p) => {
          return this.renderInputNumber(h, {key: 'defaultFee', v: p.row.defaultFee, row: p.row, min: 0, precision: 2})
        }
      }, {
        title: '续件(个)',
        key: 'extraNum',
        width: 120,
        align: 'center',
        render: (h, p) => {
          return this.renderInputNumber(h, {key: 'extraNum', v: p.row.extraNum, row: p.row, min: 1, precision: 0})
        }
      }, {
        title: '续费(元)',
        key: 'extraFee',
        width: 120,
        align: 'center',
        render: (h, p) => {
          return this.renderInputNumber(h, {key: 'extraFee', v: p.row.extraFee, row: p.row, min: 0, precision: 2})
        }
      }, {
        title: '配送描述',
        key: 'deliveryDescribe',
        minWidth: 300,
        render: (h, p) => {
          return h('Input', {
            props: {
              value: p.row.deliveryDescribe,
              placeholder: '最多100字',
              maxlength: 100
            },
            on: {
              'on-blur': (e) => {
                p.row.deliveryDescribe = e.target.value
                this.onBlur(p.row, 1)
              }
            }
          })
        }
      }, {
        title: '操作',
        width: 100,
        render: (h, p) => {
          return renderButton(h, {text: '删除', type: 'primary', size: 'small'}, () => this.onDel(p.row, 1))
        }
      }],
      columns3: [{
        title: '经销商',
        key: 'distributorDTOS',
        minWidth: 100,
        render: (h, p) => {
          let text = ''
          if (p.row.distributorDTOS && p.row.distributorDTOS.length) {
            p.row.distributorDTOS.forEach(item => {
              text += item.value + ','
            })
          }
          if (text.length) text = text.substring(0, text.length - 1)
          return (
            <div>
              <p>{text}</p>
              {renderButton(h, {text: '编辑', type: 'primary', size: 'small'}, () => this.onEdit(p.row, 'delivery'))}
            </div>
            )
        }
      }, {
        title: '首重(kg)',
        key: 'defaultNum',
        width: 110,
        render: (h, p) => {
          return this.renderInputNumber(h, {key: 'defaultNum', v: p.row.defaultNum, row: p.row, min: 0, precision: 0})
        }
      }, {
        title: '首费(元)',
        key: 'defaultFee',
        width: 110,
        render: (h, p) => {
          return this.renderInputNumber(h, {key: 'defaultFee', v: p.row.defaultFee, row: p.row, min: 0, precision: 2})
        }
      }, {
        title: '续重(kg)',
        key: 'extraNum',
        width: 110,
        render: (h, p) => {
          return this.renderInputNumber(h, {key: 'extraNum', v: p.row.extraNum, row: p.row, min: 0, precision: 0})
        }
      }, {
        title: '续费(元)',
        key: 'extraFee',
        width: 110,
        render: (h, p) => {
          return this.renderInputNumber(h, {key: 'extraFee', v: p.row.extraFee, row: p.row, min: 0, precision: 2})
        }
      }, {
        title: '配送描述',
        key: 'deliveryDescribe',
        minWidth: 300,
        render: (h, p) => {
          return h('Input', {
            props: {
              value: p.row.deliveryDescribe,
              placeholder: '最多100字',
              maxlength: 100
            },
            on: {
              'on-blur': (e) => {
                p.row.deliveryDescribe = e.target.value
                this.onBlur(p.row, 1)
              }
            }
          })
        }
      }, {
        title: '操作',
        width: 100,
        render: (h, p) => {
          return renderButton(h, {text: '删除', type: 'primary', size: 'small'}, () => this.onDel(p.row, 1))
        }
      }],
      data1: [],
      data2: [],
      isOpenFree: true,
      columns2: [{
        title: '运送到',
        key: 'distributorDTOS',
        minWidth: 100,
        render: (h, p) => {
          let text = ''
          if (p.row.distributorDTOS && p.row.distributorDTOS.length) {
            p.row.distributorDTOS.forEach(item => {
              text += item.value + ','
            })
          }
          if (text.length) text = text.substring(0, text.length - 1)
          return (
            <div>
              <p>{text}</p>
              {renderButton(h, {text: '编辑', type: 'primary', size: 'small'}, () => this.onEdit(p.row, 'postage'))}
            </div>
            )
        }
      }, {
        title: '设置包裹数',
        key: 'freeNum',
        width: 260,
        render: (h, p) => {
          return (
            <p>满{this.renderInputNumber(h, {key: 'freeNum', v: p.row.freeNum, row: p.row, min: 0, precision: 2})}件，免运费</p>
          )
        }
      }, {
        title: '配送描述',
        key: 'deliveryDescribe',
        minWidth: 300,
        render: (h, p) => {
          return h('Input', {
            props: {
              value: p.row.deliveryDescribe,
              placeholder: '最多100字',
              maxlength: 100
            },
            on: {
              'on-blur': (e) => {
                p.row.deliveryDescribe = e.target.value
                this.onBlur(p.row, 2)
              }
            }
          })
        }
      }, {
        title: '操作',
        width: 100,
        render: (h, p) => {
          return renderButton(h, {text: '删除', type: 'primary', size: 'small'}, () => this.onDel(p.row, 2))
        }
      }],
      data3: [],
      data4: []
    }
  },
  methods: {
    updateForm(id, isDefault=false) {
      this.resetForm()
      this.id = id
      this.title = this.id ? '修改单品运费模板' : '创建单品运费模板'
      this.isDefault = isDefault
      if (id) {
        this.getInfo(id)
      }
      this.modal = true
    },
    resetForm() {
      this.originalData = {}
      this.data1 = []
      this.data2 = []
      this.data3 = []
      this.data4 = []
      this.id1 = null
      this.defaultdistributorDTOS1 = []
      this.defaultNum1 = null
      this.defaultFee1 = null
      this.extraNum1 = null,
      this.extraFee1 = null,
      this.deliveryDescribe1 = ''
      this.id2 = null
      this.defaultdistributorDTOS2 = []
      this.defaultNum2 = null
      this.defaultFee2 = null
      this.extraNum2 = null
      this.extraFee2 = null
      this.deliveryDescribe2 = ''
      this.isOpenFree = true
      this.disabled = false
      this.form.freightName = ''
      this.form.freightRule = 'ITEM'
      this.form.freightCover = 'BUYER_BEAR'
    },
    getInfo(id) {
      let params = {
        id
      }
      this.$ajaxGet('/freight/setting/detail', params).then(data => {
        this.originalData = data
        this.form.freightName = data.freightName
        if (this.isDefault && !this.form.freightName) this.form.freightName = '普通配送'
        this.form.freightRule = data.freightRule
        this.form.freightCover = data.freightCover
        this.isOpenFree = data.isOpenFree
        let freightTemplateItemDTOS = data.freightTemplateItemDTOS
        let defaultArr = freightTemplateItemDTOS.filter(item => item.isDefault)
        let coverArr = freightTemplateItemDTOS.filter(item => !item.isDefault && item.freightType === 'FREIGHT')
        let freeArr = freightTemplateItemDTOS.filter(item => !item.isDefault && item.freightType === 'FREIGHT_FREE')
        coverArr.forEach(item => {
          let distributorDTOS = (item.distributorDTOS || []).map(m => {
            return {
              value: m.distributorName,
              id: m.distributorId
            }
          })
          item.distributorDTOS = distributorDTOS
        })
        freeArr.forEach(item => {
          let distributorDTOS = (item.distributorDTOS || []).map(m => {
            return {
              value: m.distributorName,
              id: m.distributorId
            }
          })
          item.distributorDTOS = distributorDTOS
        })
        let num = null
        if (this.form.freightRule === 'ITEM') {
          num = 1
        } else {
          num = 2
        }
        defaultArr.forEach(item => {
          this['defaultNum' + num] = item.defaultNum
          this['defaultFee' + num] = item.defaultFee
          this['extraNum' + num] = item.extraNum
          this['extraFee' + num] = item.extraFee
          this['deliveryDescribe' + num] = item.deliveryDescribe
          this['id' + num] = item.id
          if (item.distributorDTOS && item.distributorDTOS.length) {
            this['defaultdistributorDTOS' + num] = item.distributorDTOS.map(n => {
              return {
                value: n.distributorName,
                id: n.distributorId
              }
            })
          }
        })
        this['data' + num] = coverArr
        if (this.isOpenFree) {
          if (this.form.freightRule === 'ITEM') {
            this.data3 = freeArr
          } else {
            this.data4 = freeArr
          }
        }
      })
    },
    onBlur(row, type) {
      let num = null
      if (type === 1) {
        if (this.form.freightRule === 'ITEM') { // 按件数
          num = 1
        } else { // 按重量
          num = 2
        }
      } else if (type === 2) { // 免邮区域
        if (this.form.freightRule === 'ITEM') { // 按件数
          num = 3
        } else { // 按重量
          num = 4
        }
      }
      let params = {
        describeName: typeof row === 'string' ? this[row] : row.deliveryDescribe,
        id: typeof row === 'string' ? this['id' + num] : row.id
      }
      this.$ajaxPost('/freight/setting/describe/exist', params).then(data => {
        if (data) {
          this.$Notice.warning({
            title: '配送描述不可重复'
          })
        }
        if (typeof row === 'string') {
          this[row] = data ? '' : this[row]
        } else {
          if (data) {
            if (num) this.$set(this['data' + num][row._index], 'deliveryDescribe', '')
          } else {
            if (num) this.$set(this['data' + num][row._index], 'deliveryDescribe', row.deliveryDescribe)
          }
        }
      })
    },
    onSave() {
      if (this.disabled) return
      this.disabled = true
      this.$refs.form.validate(valid => {
        if (valid) {
          let text = ''
          let num = 1
          if (this.form.freightCover === 'BUYER_BEAR') { // 买家承担运费
            if (this.form.freightRule === 'ITEM') {
              num = 1
            } else {
              num = 2
            }
            if (!this['defaultNum' + num] || (!this['defaultFee' + num] && this['defaultFee' + num] != 0) || !this['extraNum' + num] || (!this['extraFee' + num] && this['extraFee' + num] != 0) || !this['deliveryDescribe' + num]) {
              text = '请填写完整配送区域的默认信息'
            }
            this['data' + num].forEach(item => {
              if (!item.defaultNum || (!item.defaultFee && item.defaultFee != 0) || !item.extraNum || (!item.extraFee && item.extraFee != 0) || !item.deliveryDescribe) text = '请填写完整配送区域表格信息'
            })
            if (this.isOpenFree) {
              if (this.form.freightRule === 'ITEM') {
                if (!this.data3.length) text = '请填写完整按件免邮区域表格信息'
                this.data3.forEach(item => {
                  if (!item.freeNum || !item.deliveryDescribe) text = '请填写完整按件免邮区域表格信息'
                })
              } else {
                if (!this.data4.length) text = '请填写完整按件免邮区域表格信息'
                this.data4.forEach(item => {
                  if (!item.freeNum || !item.deliveryDescribe) text = '请填写完整按件免邮区域表格信息'
                })
              }
            }
            if (text) {
              this.disabled = false
              this.$Notice.warning({
                title: text
              })
              return
            }
          }
          let param = {
            freightName: this.form.freightName,
            freightType: 'PRODUCT_FREIGHT',
            freightCover: this.form.freightCover,
            freightRule: this.form.freightRule,
            isOpenFree: this.isOpenFree,
            id: this.id
          }
          let freightTemplateItemDTOS = []
          if (this.form.freightCover === 'BUYER_BEAR') {
            if (this.form.freightRule === 'ITEM') {
              freightTemplateItemDTOS = this.fillData(1)
            } else {
              freightTemplateItemDTOS = this.fillData(2)
            }
            if (this.isOpenFree) { // 按件免邮
              let count = 3
              if (this.form.freightRule === 'WEIGHT') count = 4
              this['data' + count].forEach(item => {
                let distributorIds = item.distributorDTOS.map(m => m.id)
                freightTemplateItemDTOS.push({
                  distributorIds: distributorIds,
                  freightType: 'FREIGHT_FREE',
                  freeNum: item.freeNum,
                  deliveryDescribe: item.deliveryDescribe,
                  isDefault: false,
                  id: item.id || null
                })
              })
            }
            param.freightTemplateItemDTOS = freightTemplateItemDTOS
          } else {
            if (this.id) {
              param = {...this.originalData}
            } else {
              param.freightName = this.form.freightName
              param.freightRule = 'ITEM'
              delete param.isOpenFree
            }
            param.freightType = 'PRODUCT_FREIGHT'
            param.freightCover = 'SELLER_BEAR'
          }
          let url = this.id ? '/freight/setting/update' : '/freight/setting/save'
          this.$jsonPost(url, param).then(() => {
            this.disabled = false
            this.$Notice.success({
              title: '操作成功'
            })
            this.$emit('onFinish')
            this.modal = false
          }).catch(() => {
            this.disabled = false
          })
        } else {
          this.disabled = false
        }
      })
    },
    onDel(row, type) {
      let num = 1
      if (type === 1 && this.form.freightRule === 'WEIGHT') num = 2
      if (type === 2 && this.form.freightRule === 'ITEM') num = 3
      if (type === 2 && this.form.freightRule === 'WEIGHT') num = 4
      this['data' + num].splice(row._index, 1)
    },
    onEdit(row, type) {
      this.$refs['dealer-change'].onOpen(row._index, type, row.distributorDTOS)
    },
    onAddDealer(type) {
      let num = null
      if (type === 'delivery') { // 配送区域
        if (this.form.freightRule === 'ITEM') {
          num = 1
        } else {
          num = 2
        }
      } else { // 按件免邮区域
        if (this.form.freightRule === 'ITEM') {
          num = 3
        } else {
          num = 4
        }
      }
      if (num === 1 || num === 2) {
        this['data' + num].push({
          distributorDTOS: [],
          defaultNum: null,
          defaultFee: null,
          extraNum: null,
          extraFee: null,
          deliveryDescribe: ''
        })
      }
      if (num === 3 || num === 4) {
        this['data' + num].push({
          distributorDTOS: [],
          freeNum: null,
          deliveryDescribe: ''
        })
      }
    },
    onComplete(obj) {
      if (obj.type === 'delivery') { // 配送区域
        if (this.form.freightRule === 'ITEM') { // 按件数
          this.$set(this.data1[obj.index], 'distributorDTOS', obj.caggiageDealeredList)
        } else { // 按重量
          this.$set(this.data2[obj.index], 'distributorDTOS', obj.caggiageDealeredList)
        }
      } else if (obj.type === 'postage') { // 按件免邮区域postage
        if (this.form.freightRule === 'ITEM') {
          this.$set(this.data3[obj.index], 'distributorDTOS', obj.caggiageDealeredList)
        } else {
          this.$set(this.data4[obj.index], 'distributorDTOS', obj.caggiageDealeredList)
        }
      } else if (obj.type === 'default') {
        this['defaultdistributorDTOS' + obj.index] = obj.caggiageDealeredList
      }
    },
    onChange() {
      if (this.form.freightCover === 'SELLER_BEAR') {
        this.$Modal.confirm({
          title: "提示",
          content: "选择“卖家承担运费”后，所有区域的运费都将不生效",
          onOk: () => {
            this.form.freightCover = 'SELLER_BEAR'
          },
          onCancel: () => {
            this.form.freightCover = 'BUYER_BEAR'
          }
        })
      }
    },
    onChangeRule() {
      if (this.form.freightRule === 'WEIGHT') {
        this.$Modal.confirm({
          title: "提示",
          content: `<p class="bold">确认切换计费规则吗？</p><br/>按重量设置时商品中的重量字段为必填，如未设置则可能出现订单运费为0`,
          onOk: () => {
            this.form.freightRule = 'WEIGHT'
          },
          onCancel: () => {
            this.form.freightRule = 'ITEM'
          }
        })
      }
    },
    renderInputNumber(h, param) {
      const setData = (e) => {
        if (param.key === 'freeNum') {
          if (this.form.freightRule === 'ITEM') this.data3[param.row._index].freeNum = e
          if (this.form.freightRule === 'WEIGHT') this.data4[param.row._index].freeNum = e
        } else if (this.form.freightRule === 'ITEM') {
          this.data1[param.row._index][param.key] = e
        } else {
          this.data2[param.row._index][param.key] = e
        }
      }
      return (<InputNumber value={param.v} style="width:100px" min={param.min} onOn-change={setData} precision={param.precision}></InputNumber>)
    },
    async checkOnly() {
      let param = {
        freightName: this.form.freightName,
        id: this.id
      }
      await this.$ajaxPost('/freight/setting/name/exist', param).then(data => {
        this.flag = data
      })
    },
    fillData(type) {
      let arr = []
      let defaultdistributorIds = this['defaultdistributorDTOS' + type].map(m => m.id)
      arr.push({
        distributorIds: defaultdistributorIds,
        freightType: 'FREIGHT', 
        defaultNum: this['defaultNum' + type],
        defaultFee: this['defaultFee' + type],
        extraNum: this['extraNum' + type],
        extraFee: this['extraFee' + type],
        deliveryDescribe: this['deliveryDescribe' + type],
        isDefault: true,
        id: this['id' + type]
      })
      this['data' + type].forEach(item => {
        let distributorIds = item.distributorDTOS.map(m => m.id)
        arr.push({
          distributorIds: distributorIds,
          freightType: 'FREIGHT', // 0-运费,1-免运费
          defaultNum: item.defaultNum,
          defaultFee: item.defaultFee,
          extraNum: item.extraNum,
          extraFee: item.extraFee,
          deliveryDescribe: item.deliveryDescribe,
          isDefault: false,
          id: item.id || null
        })
      })
      return arr
    }
  },
  filters: {
    fliterDis (arr) {
      let text = ''
      arr.forEach(item => {
        text += item.value + ' , '
      })
      text = text.substring(0, text.length - 2)
      return text
    }
  }
}
</script>